
//abcd -> <Buffer 61 62 63 64>
export const string2Buff = (ab: string): Buffer => {
    // let v = new Uint8Array(ab);
    return Buffer.from(ab);
};

// <Buffer 61 62 63 64> -> [0x61 ,0x62 ,0x63, 0x64]
export const buff2Array = (buff: Buffer) => {
    return Array.prototype.slice.call(buff, 0);
};

//61626364 -> <Buffer 61 62 63 64>
export const hexString2Buff = (ab: string): Buffer => {
    return Buffer.from(ab, "hex");
};

//[ 97, 98, 99, 100 ] ->  <Buffer 61 62 63 64>
export const array2Buff = (arr: Array<number>) => {
    return  Buffer.from(arr);
};

//在client 端，只支持 arrayBuffer

// [0x61 ,0x62 ,0x63, 0x64] -> abcd
export const array2String = (arr: Array<number>) => {
  //return Buffer.from(arr).toString();
  return String.fromCharCode.apply(null, new Uint16Array(arr));
};

// abcd-1234567890 ->[97, 98, 99, 100, 45, 49,50, 51, 52,  53, 54, 55,56, 57, 48]
export const string2Array =(str:string) =>{
  var bufView = [];
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return bufView;
};

export const arrayBuffer2String = (bff: Uint16Array) => {
  return String.fromCharCode.apply(null, bff);
};

//
export const string2ArrayBuffer =(str:string) =>{
    var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
    }
    return buf;
};


